import copy
import hashlib
import os
import random
import re
import time
from datetime import datetime
from typing import Optional
from src import settings

"""将字符串转换为 MD5 哈希值"""
def convert_md5(input_string) -> str:
    # 创建一个 md5 对象
    md5_hash = hashlib.md5()
    # 更新数据（需要编码为字节）
    md5_hash.update(input_string.encode('utf-8'))
    # 获取十六进制表示的哈希值
    return md5_hash.hexdigest()

"""暂停2-4秒时间"""
def sleep_short_random():
    time.sleep(random.randrange(200, 300) / 100.0)

"""暂停5-8秒时间"""
def sleep_medium_random():
    time.sleep(random.randrange(500, 800) / 100.0)

"""暂停15-20秒时间"""
def sleep_long_random():
    time.sleep(random.randrange(1500, 2000) / 100.0)

"""暂停30-40秒时间"""
def sleep_huge_random():
    time.sleep(random.randrange(3000, 4000) / 100.0)

"""转为标准时间字符串"""
def convert_standard_datetime(datetime_str:str,input_format:str)-> Optional[str]:
    if datetime_str is None or datetime_str == "":
        return None
    if input_format is None or input_format == "":
        return datetime_str
    try:
        dt = datetime.strptime(datetime_str.strip(),input_format)
        return dt.strftime(settings.STANDARD_DATETIME_FORMATTER)
    except ValueError:
        return None

"""从无年份的时间，转为标准时间字符串"""
def convert_datetime_from_no_year(datetime_str:str, input_format: str)-> str:
    pre_year = str(int(datetime.now().strftime("%Y")) - 1)
    curr_year = datetime.now().strftime("%Y")
    next_year = str(int(datetime.now().strftime("%Y")) + 1)
    pre_datetime = datetime.strptime(pre_year + "-" +datetime_str, f"%Y-{input_format}")
    curr_datetime = datetime.strptime(curr_year + "-"+ datetime_str, f"%Y-{input_format}")
    next_datetime = datetime.strptime(next_year + "-"+ datetime_str, f"%Y-{input_format}")
    pre_diff = datetime.now() - pre_datetime
    curr_diff = datetime.now() - curr_datetime
    next_diff = next_datetime - datetime.now()
    pre_diff_seconds = pre_diff.total_seconds()
    curr_diff_seconds = abs(curr_diff.total_seconds())
    next_diff_seconds = next_diff.total_seconds()
    if pre_diff_seconds < curr_diff_seconds:
        convert_time = pre_datetime.strftime(settings.STANDARD_DATETIME_FORMATTER)
    elif next_diff_seconds < curr_diff_seconds:
        convert_time = next_datetime.strftime(settings.STANDARD_DATETIME_FORMATTER)
    else:
        convert_time = curr_datetime.strftime(settings.STANDARD_DATETIME_FORMATTER)
    return convert_time

"""格式化html中的text格式"""
def formatter_html_text(html_text: Optional[str]) -> Optional[str]:
    if html_text is None:
        return None
    cp_text = copy.deepcopy(html_text)
    cp_text = re.sub(r"\s+", " ", cp_text)
    cp_text = cp_text.replace("\xa0", "")
    cp_text = cp_text.replace("\u3000", "")
    cp_text = cp_text.replace("&nbsp;", " ")
    return cp_text.strip()

"""提取第一组两个分隔符之间的字符串"""
def extract_between_chars(input_str:Optional[str], start_delim:str, end_delim:str) -> Optional[str]:
    if input_str is None or input_str == "":
        return None
    start_index = input_str.find(start_delim) + len(start_delim)
    if start_index == -1:
        start_index = 0  # 如果未找到起始分隔符，则视作0开始
    end_index = input_str.find(end_delim, start_index)
    if end_index == -1:
        return input_str[start_index:]
    else:
        return input_str[start_index:end_index]

"""提取所有两个分隔符之间的字符串"""
def extract_all_between_chars(input_str:Optional[str], start_delim:str, end_delim:str) -> list:
    if input_str is None or input_str == "":
        return []
    pattern = re.escape(start_delim) + r'(.*?)' + re.escape(end_delim)
    return re.findall(pattern, input_str)

""" 移除两个分隔符之间的字符串"""
def remove_all_between_chars(input_str:Optional[str], start_delim:str, end_delim:str) -> Optional[str]:
    if input_str is None or input_str == "":
        return None
    pattern = re.escape(start_delim) + r'.*?' + re.escape(end_delim)
    return re.sub(pattern, '', input_str)

"""保存文本到文件"""
def save_text_to_file(path: str, data):
    file_dir = os.path.dirname(path)
    if not os.path.exists(file_dir) or not os.path.isdir(file_dir):
        os.makedirs(file_dir)
    f2 = open(path, 'w', encoding='utf-8')
    try:
        f2.write(str(data))
    finally:
        f2.close()

"""保存二进制到文件"""
def save_byte_to_file(path: str, data):
    file_dir = os.path.dirname(path)
    if not os.path.exists(file_dir) or not os.path.isdir(file_dir):
        os.makedirs(file_dir)

    f2 = open(path, 'wb')
    try:
        f2.write(data)
    finally:
        f2.close()

"""从文件中加载文本"""
def load_text_from_file(path) -> Optional[str]:
    if not os.path.exists(path):
        return None
    with open(path, 'r',encoding='utf-8') as file:
        return file.read()

"""从文件中加载二进制"""
def load_byte_from_file(path) -> Optional[bytes]:
    if not os.path.exists(path):
        return None
    with open(path, 'rb') as file:
        return file.read()
